package store.lunangangster.nodeflow.context.holder;

import java.util.Comparator;
import java.util.ServiceLoader;
import java.util.TreeSet;
import store.lunangangster.nodeflow.context.NodesInitializer;
import store.lunangangster.nodeflow.context.Order;

/**
 * 用于保存和获取NodesInitializer的类
 *
 * @author cwk
 * @version 1.0
 */
public class NodesInitializerHolder {
	private static volatile NodesInitializer initializer;

	private static final TreeSet<NodesInitializer> initializerSet = new TreeSet<>(Comparator.comparingInt(
			Order::priority));

	/**
	 * 通过spi获取相应的节点初始化器。
	 * <p>对于本地环境，没有任何的初始化器
	 * <p>对于Spring环境，会有一个全局的扫描器用来扫描NodeComponent对象，并且将其加入到FlowBus中
	 * @return	节点初始化器
	 */
	public static NodesInitializer getInitializer() {
		if (initializer == null) {
			synchronized (NodesInitializerHolder.class) {
				if (initializer == null) {
					ServiceLoader<NodesInitializer> serviceLoader = ServiceLoader.load(NodesInitializer.class);
					serviceLoader.forEach(initializerSet::add);
					initializer = initializerSet.first();
					initializerSet.clear();
				}
			}
		}
		return initializer;
	}
}
